package com.mycode.finance.controller.app;

import com.mycode.finance.common.ErrorPageConfig;
import com.mycode.finance.entity.*;
import com.mycode.finance.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author nbly
 * @version 1.0
 * @description: TODO
 * @date 2025/4/30 10:31
 */
@Component
public class InfoTaskController {

    private static final Logger logger = LoggerFactory.getLogger(InfoTaskController.class);

    @Autowired
    UserService userService;
    @Autowired
    UserChangeMoneyService userChangeMoneyService;
    @Autowired
    UserPayMoneyService userPayMoneyService;
    @Autowired
    UserFundProductService userFundProductService;
    @Autowired
    UserTermFinancialService userTermFinancialService;
    @Autowired
    InfoService infoService;

    @Scheduled(cron = "0 0 0 * * ?")
    public void handleAdvent() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        logger.info(sdf.format(new Date()) + "开始执行定时任务");
        List<User> userList = userService.selectAllUser();
        long tenDaysInMillis = 10 * 24 * 60 * 60 * 1000; // 10天的时间戳
        List<Info> infoList = new ArrayList<>();
        long nowDate = new Date().getTime();
        if (userList.size() > 0) {
            userList.forEach(user -> {
                Integer userId = user.getId();
                // 零钱理财
                List<UserChangeMoney> userChangeMoneyList = userChangeMoneyService.selectUserChangeMoneyByUserId(userId);
                if (userChangeMoneyList.size() > 0)
                    userChangeMoneyList.forEach(item -> {
                        if (item.getStatus() == 1) { // 持有中
                            // 判断事件
                            Date starttime = item.getStarttime();
                            int investerm = convertInvest(item.getChangeMoney().getInvesterm());
                            long validDate = plusDays(starttime, investerm);
                            if (nowDate < validDate && (validDate - nowDate < tenDaysInMillis)) {
                                Info info = new Info();
                                info.setSendid(userId);
                                info.setReceiveid(userId);
                                info.setCreatetime(new Date());
                                info.setTitle(item.getChangeMoney().getName() + "零钱理财10天到期提醒");
                                info.setInfodesc("用户" + user.getUsername() + "的" + item.getChangeMoney().getName() + "零钱理财到期还有十天！");
                                info.setStatus(0);
                                infoList.add(info);
                            }
                        }
                    });
                // 工资理财
                List<UserPayMoney> userPayMoneyList = userPayMoneyService.selectUserPayMoneyByUserId(userId);
                if (userPayMoneyList.size() > 0)
                    userPayMoneyList.forEach(item -> {
                        if (item.getStatus() == 1) {
                            // 获取开始时间
                            Date starttime = item.getStarttime();
                            int investerm = convertInvest(item.getPayMoney().getInvesterm());
                            long validDate = plusDays(starttime, investerm);
                            if (nowDate < validDate && (validDate - nowDate < tenDaysInMillis)) {
                                Info info = new Info();
                                info.setSendid(userId);
                                info.setReceiveid(userId);
                                info.setCreatetime(new Date());
                                String name = item.getPayMoney().getType() == 1 ? "国债" : "期货";
                                info.setTitle(item.getPayMoney().getId() + "号" + name + "工资理财10天到期提醒");
                                info.setInfodesc("用户" + user.getUsername() + "的" + item.getPayMoney().getId() + "号" + name + "工资理财到期还有十天！");
                                info.setStatus(0);
                                infoList.add(info);
                            }
                        }
                    });
                // 期限理财
                List<UserTermFinancial> userTermFinancialList = userTermFinancialService.selectUserTermFinancialByUserId(userId);
                if (userTermFinancialList.size() > 0) {
                    userTermFinancialList.forEach(item -> {
                        if (item.getStatus() == 1) {
                            Date starttime = item.getStarttime();
                            int investerm = convertInvest(item.getTermFinancial().getInvesterm());
                            long validDate = plusDays(starttime, investerm);
                            if (nowDate < validDate && (validDate - nowDate < tenDaysInMillis)) {
                                Info info = new Info();
                                info.setSendid(userId);
                                info.setReceiveid(userId);
                                info.setCreatetime(new Date());
                                info.setTitle(item.getTermFinancial().getName() + "期限理财10天到期提醒");
                                info.setInfodesc("用户" + user.getUsername() + "的" + item.getTermFinancial().getName() + "期限理财到期还有十天！");
                                info.setStatus(0);
                                infoList.add(info);
                            }
                        }
                    });
                }
                // 基金理财
                List<UserFundProduct> userFundProductList = userFundProductService.selectUserFundProductByUserId(userId);
                if (userFundProductList.size() > 0) {
                    userFundProductList.forEach(item -> {
                        if (item.getStatus() == 1) {
                            Date starttime = item.getStarttime();
                            int investerm = convertInvest(item.getFundProduct().getInvesterm());
                            long validDate = plusDays(starttime, investerm);
                            if (nowDate < validDate && (validDate - nowDate < tenDaysInMillis)) {
                                Info info = new Info();
                                info.setSendid(userId);
                                info.setReceiveid(userId);
                                info.setCreatetime(new Date());
                                info.setTitle(item.getFundProduct().getFunddesc() + "基金理财10天到期提醒");
                                info.setInfodesc("用户" + user.getUsername() + "的" + item.getFundProduct().getFunddesc() + "基金理财到期还有十天！");
                                info.setStatus(0);
                                infoList.add(info);
                            }
                        }
                    });
                }
            });
        }
        if (infoList.size() > 0) {
            infoList.forEach(info -> {
                Info findInfo = infoService.selectInfoByTitle(info.getTitle());
                if (findInfo == null) {
                    infoService.insertInfo(info);
                    logger.info("发送通知：" + info.getTitle());
                }
            });
        }
    }

    private long plusDays(Date starttime, int days) {
        Instant instant = starttime.toInstant();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        LocalDateTime validDateTime = localDateTime.plusDays(days);
        Instant instant1 = validDateTime.atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant1).getTime();
    }

    private int convertInvest(String investerm) {
        int day = 0;
        // 处理天
        if (investerm.indexOf("天") > 0) {
            try {
                day = Integer.parseInt(investerm.replace("天", ""));
            } catch (Exception e) {
                return 0;
            }
        }
        // 处理月
        if (investerm.indexOf("月") > 0) {
            String month = investerm.replace("个月", "");
            switch (month) {
                case "一":
                    return 30;
                case "二":
                    return 60;
                case "三":
                    return 90;
                case "四":
                    return 120;
                case "五":
                    return 150;
                case "六":
                    return 180;
                case "七":
                    return 210;
                case "八":
                    return 240;
                case "九":
                    return 270;
                case "十":
                    return 300;
                case "十一":
                    return 330;
                case "十二":
                    return 360;
            }
        }
        // 处理年
        if (investerm.indexOf("年") > 0) {
            String year = investerm.replace("年", "");
            switch (year) {
                case "半":
                    return 183;
                case "一":
                    return 365;
                case "二":
                    return 730;
                case "三":
                    return 1095;
                case "四":
                    return 1460;
                case "五":
                    return 1825;
                case "六":
                    return 2190;
                case "七":
                    return 2550;
                case "八":
                    return 2925;
                case "九":
                    return 3300;
                case "十":
                    return 3650;
            }
        }
        return day;
    }
}
